<template>
  <t-checkbox v-model="isSelectedAll" :indeterminate="isIndeterminate" @change="toggleSelectedCheckbox">全选</t-checkbox>

  <t-checkbox-group v-model="checkedCities">
    <t-checkbox v-for="city in citeOptions" :label="city" :key="city">{{ city }}</t-checkbox>
  </t-checkbox-group>
</template>

<script lang="ts">
import TCheckboxGroup from "@t-ui/checkbox/src/checkbox-group.vue";
import TCheckbox from "@t-ui/checkbox/src/index.vue";
import {computed, ref} from "vue";

function useIndeterminate<T = any>(options: T[], defaultOptions = []) {
  const checked = ref(defaultOptions)
  const checkedCount = computed(() => checked.value.length)
  const isIndeterminate = computed(() => {
    return checkedCount.value > 0 && checkedCount.value < (options?.length || 0)
  })
  const isSelectedAll = computed(() => {
    return checkedCount.value > 0 && checkedCount.value === (options?.length || 0)
  })
  const toggleSelectedCheckbox = () => {
    isSelectedAll.value
        ? checked.value = []
        : checked.value = [].concat(options)
  }

  return {
    checked,
    isIndeterminate,
    isSelectedAll,
    toggleSelectedCheckbox
  }
}

export default {
  components: {TCheckbox, TCheckboxGroup},
  setup() {
    const citeOptions = ['上海', '北京', '广州', '深圳']

    const {
      checked: checkedCities,
      isIndeterminate,
      isSelectedAll,
      toggleSelectedCheckbox
    } = useIndeterminate(citeOptions, ['上海', '北京'])

    return {
      checkedCities,
      isSelectedAll,
      isIndeterminate,
      toggleSelectedCheckbox,

      citeOptions
    }
  }
}
</script>
